import 'package:get/get.dart';
import '../data/models/user_model.dart';
import '../domain/services/auth_business.dart';
import '../domain/services/user_business.dart';
import '../../core/base/base_controller.dart';
import '../services/storage/local_storage_service.dart';
import '../routes/app_routes.dart';

/// 认证控制器
class AuthController extends BaseController {
  /// 认证业务服务
  final AuthBusiness _authBusiness;
  
  /// 用户业务服务
  final UserBusiness _userBusiness;
  
  /// 本地存储服务
  final LocalStorageService _storageService;
  
  /// 当前用户
  final Rx<UserModel?> _currentUser = Rx<UserModel?>(null);
  
  /// 是否已认证
  final RxBool _isAuthenticated = false.obs;
  
  /// 认证令牌
  final RxString _token = ''.obs;
  
  /// 刷新令牌
  final RxString _refreshToken = ''.obs;
  
  /// 是否记住登录状态
  final RxBool _rememberMe = false.obs;
  
  /// 获取当前用户
  UserModel? get currentUser => _currentUser.value;
  
  /// 是否已认证
  bool get isAuthenticated => _isAuthenticated.value;
  
  /// 获取认证令牌
  String get token => _token.value;
  
  /// 获取刷新令牌
  String get refreshToken => _refreshToken.value;
  
  /// 是否记住登录状态
  bool get rememberMe => _rememberMe.value;
  
  /// 设置记住登录状态
  set rememberMe(bool value) => _rememberMe.value = value;
  
  /// 构造函数
  AuthController({
    required AuthBusiness authBusiness,
    required UserBusiness userBusiness,
    required LocalStorageService storageService,
  }) 
    : _authBusiness = authBusiness,
      _userBusiness = userBusiness,
      _storageService = storageService;
  
  @override
  void onInit() {
    super.onInit();
    _initAuth();
  }
  
  /// 初始化认证状态
  Future<void> _initAuth() async {
    // 从本地存储中获取认证信息
    final String? storedToken = await _storageService.getToken();
    final String? storedRefreshToken = await _storageService.getRefreshToken();
    
    if (storedToken != null && storedToken.isNotEmpty) {
      _token.value = storedToken;
      
      if (storedRefreshToken != null && storedRefreshToken.isNotEmpty) {
        _refreshToken.value = storedRefreshToken;
      }
      
      // 验证令牌的有效性
      final bool isValid = await _authBusiness.verifyToken(token: storedToken);
      
      if (isValid) {
        // 获取当前用户信息
        await _getCurrentUser();
      } else {
        // 令牌无效，尝试刷新
        await _refreshAuthToken();
      }
    }
  }
  
  /// 获取当前用户信息
  Future<void> _getCurrentUser() async {
    setLoading(true);
    
    try {
      final user = await _userBusiness.getCurrentUser();
      
      if (user != null) {
        _currentUser.value = user;
        _isAuthenticated.value = true;
      } else {
        _isAuthenticated.value = false;
        await _clearAuthData();
      }
    } catch (e) {
      _isAuthenticated.value = false;
      await _clearAuthData();
    } finally {
      setLoading(false);
    }
  }
  
  /// 刷新认证令牌
  Future<void> _refreshAuthToken() async {
    if (_refreshToken.value.isEmpty) {
      _isAuthenticated.value = false;
      await _clearAuthData();
      return;
    }
    
    try {
      final newToken = await _authBusiness.refreshToken(
        refreshToken: _refreshToken.value,
      );
      
      if (newToken != null && newToken.isNotEmpty) {
        _token.value = newToken;
        await _storageService.saveToken(newToken);
        await _getCurrentUser();
      } else {
        _isAuthenticated.value = false;
        await _clearAuthData();
      }
    } catch (e) {
      _isAuthenticated.value = false;
      await _clearAuthData();
    }
  }
  
  /// 用户登录
  Future<bool> login({
    required String username,
    required String password,
  }) async {
    setLoading(true);
    
    try {
      final user = await _authBusiness.login(
        username: username,
        password: password,
      );
      
      if (user != null) {
        _currentUser.value = user;
        _isAuthenticated.value = true;
        
        // 保存认证信息
        if (_rememberMe.value) {
          await _storageService.saveToken(_token.value);
          await _storageService.saveRefreshToken(_refreshToken.value);
        }
        
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  }
  
  /// 用户注册
  Future<bool> register({
    required String username,
    required String password,
    required String email,
    String? displayName,
    String? phone,
  }) async {
    setLoading(true);
    
    try {
      final user = await _authBusiness.register(
        username: username,
        password: password,
        email: email,
        displayName: displayName,
        phone: phone,
      );
      
      if (user != null) {
        _currentUser.value = user;
        _isAuthenticated.value = true;
        
        // 保存认证信息
        if (_rememberMe.value) {
          await _storageService.saveToken(_token.value);
          await _storageService.saveRefreshToken(_refreshToken.value);
        }
        
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  }
  
  /// 用户退出登录
  Future<void> logout() async {
    setLoading(true);
    
    try {
      await _authBusiness.logout();
    } finally {
      await _clearAuthData();
      setLoading(false);
      
      // 退出到登录页面
      Get.offAllNamed(AppRoutes.login);
    }
  }
  
  /// 清除认证数据
  Future<void> _clearAuthData() async {
    _currentUser.value = null;
    _isAuthenticated.value = false;
    _token.value = '';
    _refreshToken.value = '';
    
    // 清除本地存储中的认证信息
    await _storageService.removeToken();
    await _storageService.removeRefreshToken();
  }
  
  /// 忘记密码
  Future<bool> forgotPassword({
    required String email,
  }) async {
    setLoading(true);
    
    try {
      return await _authBusiness.forgotPassword(email: email);
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  }
  
  /// 重置密码
  Future<bool> resetPassword({
    required String token,
    required String newPassword,
  }) async {
    setLoading(true);
    
    try {
      return await _authBusiness.resetPassword(
        token: token,
        newPassword: newPassword,
      );
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  }
  
  /// 更改密码
  Future<bool> changePassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    setLoading(true);
    
    try {
      return await _userBusiness.changePassword(
        oldPassword: oldPassword,
        newPassword: newPassword,
      );
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  }
  
  /// 更新用户资料
  Future<bool> updateProfile({
    required String userId,
    String? displayName,
    String? email,
    String? phone,
    String? avatarUrl,
    String? bio,
    String? address,
    String? city,
    String? country,
    String? zipCode,
    Map<String, dynamic>? extraData,
  }) async {
    setLoading(true);
    
    try {
      final updatedUser = await _userBusiness.updateProfile(
        userId: userId,
        displayName: displayName,
        email: email,
        phone: phone,
        avatarUrl: avatarUrl,
        bio: bio,
        address: address,
        city: city,
        country: country,
        zipCode: zipCode,
        extraData: extraData,
      );
      
      if (updatedUser != null) {
        _currentUser.value = updatedUser;
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  }
  
  /// 检查用户是否有管理员权限
  bool hasAdminRole() {
    return _currentUser.value != null && 
           _userBusiness.isAdmin(_currentUser.value!);
  }
} 